package com.yswl.pri.home.vedio;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.http.okhttp.MSPUtils;
import yswl.com.klibrary.util.GsonUtil;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MKeyBoardUtils;

/**
 * 搜索
 */
public class SearchActivity extends ToolbarActivity implements View.OnClickListener, View.OnFocusChangeListener {
    private static final String TAG = SearchActivity.class.getSimpleName();
    private static final String FILE_NAME = "search_sp";
    private static final String FILE_NAME_KEY = "list";
    private static final String TYPE_1 = "MOVIE";
    private static final String TYPE_2 = "MUSIC";
    ImageButton mSearchSubmit;
    EditText mSearchEdite;
    SearchRecordListAdapter mAdapter;
    String searchType = TYPE_1;
    List<String> mRecord;
    TextView type1;
    TextView type2;

    public static void JumpAct(Context context) {
        Intent intent = new Intent(context, SearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        MKeyBoardUtils.hideSoftKeyboard(this);
        setCustomView();
        initData();
        initUI();
    }

    private void initData() {
        try {
            String recorJson = (String) MSPUtils.get(FILE_NAME, FILE_NAME_KEY, "");
            if (!TextUtils.isEmpty(recorJson)) {
                mRecord = GsonUtil.GsonToList(recorJson, String.class);
            }
        } catch (Exception e) {
        }
        if (mRecord == null)
            mRecord = new ArrayList<>();


    }


    private void setCustomView() {
        View view = LayoutInflater.from(this).inflate(R.layout.common_toolbar_search_layout, null, false);
        mSearchSubmit = view.findViewById(R.id.actionbar_search_bt);
        mSearchEdite = view.findViewById(R.id.actionbar_search_et);
        mSearchEdite.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    final String key = mSearchEdite.getText().toString();
                    searchKey(key);
                }
                return true;
            }
        });
        mSearchSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String key = mSearchEdite.getText().toString();
                searchKey(key);
            }
        });
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }


    private void initUI() {
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new SearchRecordListAdapter(this, mRecord, R.layout.adapter_search_record_item);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                searchKey(mAdapter.getList().get(position));
            }
        });

        mAdapter.setHeaderView(getHeadVeiw(recyclerView));
        mAdapter.setFooterView(getFooterView(recyclerView));
        recyclerView.setAdapter(mAdapter);
    }

    private View getHeadVeiw(ViewGroup parentViewGroup) {
        View headView = LayoutInflater.from(this).inflate(R.layout.adapter_search_record_head, parentViewGroup, false);
        type1 = headView.findViewById(R.id.type1);
        type2 = headView.findViewById(R.id.type2);
        type1.requestFocus();
        type1.setSelected(true);
        type1.setOnFocusChangeListener(this);
        type2.setOnFocusChangeListener(this);
        type1.setOnClickListener(this);
        type2.setOnClickListener(this);
        return headView;
    }

    private View getFooterView(ViewGroup parentViewGroup) {
        View footer = LayoutInflater.from(this).inflate(R.layout.adapter_search_record_item, parentViewGroup, false);
        TextView textView = footer.findViewById(R.id.tv_name);
        textView.setText("清除搜索记录");
        textView.setTextColor(Color.GREEN);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecord.clear();
                mAdapter.notifyDataSetChanged();
                clearLocalRecord();
            }
        });
        return footer;
    }

    @Override
    protected void onPause() {
        super.onPause();
        MKeyBoardUtils.hideSoftKeyboard(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.type1) {
            type2.setSelected(false);
            type1.setSelected(true);
            mSearchEdite.setHint("搜电影");
            searchType = TYPE_1;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                type2.setTextColor(getColor(R.color.text));
                type1.setTextColor(getColor(R.color.colorAccent));
            }
        } else if (v.getId() == R.id.type2) {
            type2.setSelected(true);
            type1.setSelected(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                type1.setTextColor(getColor(R.color.text));
                type2.setTextColor(getColor(R.color.colorAccent));
            }
            mSearchEdite.setHint("搜种子");
            searchType = TYPE_2;
        }
    }

    private void updateLocalRecord(List<String> newList) {
        String json = new Gson().toJson(newList);
        MSPUtils.put(FILE_NAME, FILE_NAME_KEY, json);
    }

    private void clearLocalRecord() {
        MSPUtils.clear(this, FILE_NAME);
    }

    private void searchKey(final String key) {
        if (TextUtils.isEmpty(key)) return;
        MKeyBoardUtils.closeKeybord(mSearchEdite, SearchActivity.this);
        mSearchSubmit.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mRecord.size() >= 10) {
                    mRecord.remove(9);
                }
                if (!mRecord.contains(key)) {
                    mRecord.add(0, key);
                } else {
                    int index = mRecord.indexOf(key);
                    if (index != 0) {
                        Collections.swap(mRecord, index, 0);
                    }
                }

                mAdapter.notifyDataSetChanged();
                updateLocalRecord(mRecord);
            }
        }, 1000);
        if (searchType.equals(TYPE_1))
            MovieSearchListActivity.JumpAct(SearchActivity.this, key);
        else
            MusicSearchListActivity.JumpAct(SearchActivity.this, key);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        L.e(TAG, "viewId : " + v.getId() + " hasFocus : " + hasFocus);
        if (hasFocus) {
            if (v.getId() == R.id.type1) {
                mSearchEdite.setHint("搜电影");
                type1.setSelected(true);
                type2.setSelected(false);
                searchType = TYPE_1;
            }

            if (v.getId() == R.id.type2) {
                mSearchEdite.setHint("搜种子");
                searchType = TYPE_2;
                type1.setSelected(false);
                type2.setSelected(true);
            }
        }

    }


    public class SearchRecordListAdapter extends BaseRecyclerAdapter<String> {
        public SearchRecordListAdapter(Context mContext, List<String> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
        }

        @Override
        public void onBind(BaseViewHolder holder, String title, int position) {
            TextView textView = holder.findById(R.id.tv_name);
            textView.setText(title);
        }
    }
}
